package org.cuatrovientos.erp.dao;


import java.util.List;

import org.cuatrovientos.erp.model.Message;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
 * 
 * @author CARLOS
 *
 */
public class MessageDAO implements MessageDAOInterface{


	@Autowired
	 private SessionFactory sessionFactory;
	
	public MessageDAO(){
		
	}
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	 @Transactional(readOnly = true)
		public Message selectById(int id) {
			Message message= (Message) getSession().get(Message.class, id);
		    return message;
		}

	 /*
		 * retrieves all products from db
		 * @return List of products
		 */
		 @Transactional(readOnly = true)
		public List<Message> selectAll() {
		 
		    List<Message> message = getSession().createQuery("from Message").list();
		    return message;
		}

		 /*
			 * inserts a new product in database
			 * retrieves generated id and sets to product instance
			 * @param new product
			 */
			 @Transactional
			public void insert(Message message) {
			    Integer id = (Integer) getSession().save(message);
			    message.setId(id);           
			}

				/*
				 * updates product
				 * @param product to update
				 */
				 @Transactional
				public void update(Message message) {
					getSession().merge(message);
				}

				 /*
					 * delete given product
					 * @param product to delete
					 */
					 @Transactional
					public void delete(Message message) {
						getSession().delete(message);
					}

					 /**
					  * deletes using id
					  */
					 @Transactional
					public void deleteById(int id) {
						 Message message = (Message) getSession().load(Message.class,id);
						 getSession().delete(message);
					}

					 /**
					  * performs search operation
					  */
					 @Transactional(readOnly = true)
					public List<Message> search(String title) {
						   Query query = getSession().createQuery("from Message c where c.title like :title");
				           query.setParameter("title", "%"+title+"%");
				           
				           List<Message> messages = query.list();
						
				           return messages;
					}

}
